import React, { useEffect, useState, useCallback } from 'react';
import { observer } from 'mobx-react';
import {Space, Table, Button, Modal, Form, Input} from "antd";
import envVariableStore from "../store/envVariableStore";
import HideDelete from "../../../common/hideDelete/HideDelete";
import IconCommon from "../../../common/IconCommon";

/**
 * 环境变量列表组件
 * @param {Object} props - 组件属性
 * @param {string} props.envId - 环境ID
 */
const EnvVariableTable = ({ envId }) => {
    const {
        findEnvVariableList,
        deleteEnvVariable,
        updateEnvVariable,
        createEnvVariable,
    } = envVariableStore;

    const [form] = Form.useForm();
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [editingRecord, setEditingRecord] = useState(null);
    const [dataSource, setDataSource] = useState([]);

    const columns = [
        {
            title: '变量名称',
            dataIndex: 'name',
            key: 'name',
            width: "30%",
            ellipsis: true,
        },
        {
            title: '变量值',
            dataIndex: 'value',
            key: 'value',
            width: "30%",
            ellipsis: true,
        },
        {
            title: '描述',
            dataIndex: 'desc',
            key: 'desc',
            width: "30%",
            ellipsis: true,
        },
        {
            title: '操作',
            dataIndex: 'action',
            key: 'action',
            width: "10%",
            render: (_, record) => (
                <Space size={"middle"}>
                    <IconCommon
                        icon={"bianji11"}
                        className={"icon-s edit-icon"}
                        onClick={() => handleEdit(record)}
                    />
                    <HideDelete
                        deleteFn={() => deleteEnvVariable(record.id).then(() => loadData())}
                    />
                </Space>
            )
        },
    ];

    const loadData = useCallback(async () => {
        if (envId) {
            const list = await findEnvVariableList({ envId });
            setDataSource(list);
        } else {
            setDataSource([]);
        }
    }, [envId, findEnvVariableList]);

    useEffect(() => {
        loadData();
    }, [loadData]);

    const handleEdit = (record) => {
        setEditingRecord(record);
        form.setFieldsValue(record);
        setIsModalVisible(true);
    };

    const handleAdd = () => {
        setEditingRecord(null);
        form.resetFields();
        setIsModalVisible(true);
    };

    const handleModalOk = async () => {
        try {
            const values = await form.validateFields();
            if (editingRecord) {
                await updateEnvVariable({ ...values, id: editingRecord.id });
            } else {
                await createEnvVariable({ ...values, envId });
            }
            setIsModalVisible(false);
            loadData();
        } catch (error) {
            console.error('保存失败:', error);
        }
    };

    return (
        <div className='pi-list-box'>
            <div style={{ margin: 8, display: 'flex', justifyContent: 'space-between' }}>
                <div style={{color: '#999'}}>共 {dataSource.length} 个</div>
                <Button 
                    type="primary" 
                    onClick={handleAdd}
                >
                    新建变量
                </Button>
            </div>
            <Table
                dataSource={dataSource}
                columns={columns}
                rowKey="id"
                pagination={false}
            />
            <Modal
                title={editingRecord ? "编辑变量" : "新建变量"}
                open={isModalVisible}
                onOk={handleModalOk}
                onCancel={() => setIsModalVisible(false)}
            >
                <Form
                    form={form}
                    layout="vertical"
                >
                    <Form.Item
                        name="name"
                        label="变量名称"
                        rules={[{ required: true, message: '请输入变量名称' }]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        name="value"
                        label="变量值"
                        rules={[{ required: true, message: '请输入变量值' }]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        name="desc"
                        label="描述"
                    >
                        <Input />
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    );
};

export default observer(EnvVariableTable);